/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.vod.gauss.net;

import fr.vod.gauss.File.File;
import fr.vod.gauss.matrice.Equation;
import fr.vod.gauss.matrice.EquationImpl;
import fr.vod.gauss.utils.Convert;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author drazanakoto
 */
public class FormatImpl implements Format {

	@Override
	public Equation format(byte[] msg, int blockSize, int packetSize) {
		int[] tab = new int[blockSize];
		int tmp;

		for (int i = 0; i < packetSize; i++) {
			tmp = Convert.byteToUint8(msg[File.SIZE_OF_BLOCK_NUMBER + 1 + i]);
			tab[tmp] = Convert.byteToUint8(msg[File.SIZE_OF_BLOCK_NUMBER + 1
					+ packetSize + i]);

		}
		return new EquationImpl(tab, Convert.byteToUint8(msg[msg.length - 1]));
	}

	/**
	 * 
	 * @param msg
	 * @return
	 */
	@Override
	public long getBlockNumber(byte[] msg) {
		byte[] tab = new byte[File.SIZE_OF_BLOCK_NUMBER];
		System.arraycopy(msg, 1, tab, 0, File.SIZE_OF_BLOCK_NUMBER);
		return ByteBuffer.wrap(tab).getLong();
	}

	@Override
	public boolean isXor(byte[] msg) {
		return msg[0] == 1;
	}

	@Override
	public boolean respectFormat(byte[] msg, int packetSize) {
		return (msg[0] == 1 || msg[0] == 0);
	}

	@Override
	public List<Equation> formatAllNotXor(byte[] msg, int blockSize,
			int packetSize) {
		int[] tab = null;
		int tmp;
		List<Equation> lst = new ArrayList<Equation>();
		if (respectFormat(msg, packetSize)) {
			for (int i = 0; i < packetSize; i++) {
				tmp = Convert
						.byteToUint8(msg[File.SIZE_OF_BLOCK_NUMBER + 1 + i]);
				tab = new int[blockSize];
				tab[tmp] = 1;
				lst.add(new EquationImpl(tab, msg[File.SIZE_OF_BLOCK_NUMBER + 1
						+ packetSize + i]));
			}
			return lst;
		}
		return null;
	}
}
